package com.hskn.hss.module.tlresplan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.mapper.TlCarTypeMapper;
import com.hskn.hss.module.tldictlevel.entity.TlEmergentDictLevel;
import com.hskn.hss.module.tldictlevel.mapper.TlEmergentDictLevelMapper;
import com.hskn.hss.module.tldictlevel.service.ITlEmergentDictLevelService;
import com.hskn.hss.module.tldicttype.entity.TlEmergentDictType;
import com.hskn.hss.module.tldicttype.mapper.TlEmergentDictTypeMapper;
import com.hskn.hss.module.tldicttype.service.ITlEmergentDictTypeService;
import com.hskn.hss.module.tlemergentopera.entity.TlEmergentPlanOperadetails;
import com.hskn.hss.module.tlemergentplan.entity.TlEmergentPlan;
import com.hskn.hss.module.tlemergentplan.mapper.TlEmergentPlanMapper;
import com.hskn.hss.module.tlemergentplan.vo.TlEmergentPlanVO;
import com.hskn.hss.module.tlresplan.entity.TlEmergentResplan;
import com.hskn.hss.module.tlresplan.mapper.TlEmergentResplanMapper;
import com.hskn.hss.module.tlresplan.service.ITlEmergentResplanService;
import com.hskn.hss.module.tlresplan.vo.*;
import com.hskn.hss.module.tlresplanitem.entity.TlEmergentResplanItem;
import com.hskn.hss.module.tlresplanitem.mapper.TlEmergentResplanItemMapper;
import com.hskn.hss.module.tlresplanitem.service.ITlEmergentResplanItemService;
import com.hskn.hss.module.tlservicetype.entity.TlServiceType;
import com.hskn.hss.module.tlworktype.entity.TlWorkType;
import com.hskn.hss.module.tlworktype.mapper.TlWorkTypeMapper;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.userdepart.entity.SysUserDepart;
import com.hskn.hss.module.userdepart.mapper.SysUserDepartMapper;
import com.hskn.hss.module.worktype.entity.WorkType;
import com.hskn.hss.module.worktype.mapper.WorkTypeMapper;
import com.hskn.hss.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-18
 */
@Service
public class TlEmergentResplanServiceImpl extends ServiceImpl<TlEmergentResplanMapper, TlEmergentResplan> implements ITlEmergentResplanService {

    @Resource
    TlEmergentResplanMapper tlEmergentResplanMapper;
    @Resource
    SysUserDepartMapper sysUserDepartMapper;
    @Autowired
    ITlEmergentResplanItemService tlEmergentResplanItemService;
    @Resource
    TlEmergentResplanItemMapper tlEmergentResplanItemMapper;
    @Resource
    TlEmergentPlanMapper tlEmergentPlanMapper;
    @Resource
    TlCarTypeMapper tlCarTypeMapper;
    @Resource
    TlWorkTypeMapper tlWorkTypeMapper;
    @Resource
    TlEmergentDictLevelMapper tlEmergentDictLevelMapper;
    @Resource
    TlEmergentDictTypeMapper tlEmergentDictTypeMapper;
    @Autowired
    ITlEmergentDictLevelService tlEmergentDictLevelService;
    @Autowired
    ITlEmergentResplanService tlEmergentResplanService;

    @Override
    @Transactional
    public AjaxResult insert(TlEmergentResplan tlEmergentResplan) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserDepart::getUserid, uid);
        String deptid = sysUserDepartMapper.selectOne(queryWrapper).getDepid();

        tlEmergentResplan.setCreateby(uid);
        tlEmergentResplan.setCreatetime(new Date());
        tlEmergentResplan.setDeptid(deptid);
        List<String> askcar = new ArrayList<>();
        List<String> askemp = new ArrayList<>();

        tlEmergentResplanMapper.insert(tlEmergentResplan);
        List<TlEmergentResplanItem> caritemList = tlEmergentResplan.getCardateils();
        List<TlEmergentResplanItem> empitemList = tlEmergentResplan.getEmpdateils();
        if (null != caritemList && caritemList.size() > 0) {
            for (TlEmergentResplanItem item : caritemList) {
                item.setResplanid(tlEmergentResplan.getId());
                item.setWorktype("car");
                askcar.add(item.getClassname());
                tlEmergentResplanItemService.insert(item);
            }
            tlEmergentResplan.setAskcar(String.join(",", askcar));
        }
        if (null != empitemList && empitemList.size() > 0) {
            for (TlEmergentResplanItem item : empitemList) {
                item.setResplanid(tlEmergentResplan.getId());
                item.setWorktype("emp");
                askemp.add(item.getClassname());
                tlEmergentResplanItemService.insert(item);
            }
            tlEmergentResplan.setAskemp(String.join(",", askemp));
        }

        tlEmergentResplanMapper.updateById(tlEmergentResplan);
        return AjaxResult.success("操作成功");
    }

    @Override
    @Transactional
    public AjaxResult update(TlEmergentResplan tlEmergentResplan) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        tlEmergentResplan.setUpdateby(uid);
        tlEmergentResplan.setUpdatetime(new Date());
        List<String> askcar = new ArrayList<>();
        List<String> askemp = new ArrayList<>();

        List<TlEmergentResplanItem> caritemList = tlEmergentResplan.getCardateils();
        List<TlEmergentResplanItem> empitemList = tlEmergentResplan.getEmpdateils();
        tlEmergentResplanItemService.deletebyid(tlEmergentResplan.getId());
        if (null != caritemList && caritemList.size() > 0) {
            for (TlEmergentResplanItem item : caritemList) {
                item.setResplanid(tlEmergentResplan.getId());
                item.setWorktype("car");
                askcar.add(item.getClassname());
                tlEmergentResplanItemService.insert(item);
            }
            tlEmergentResplan.setAskcar(String.join(",", askcar));
        }
        if (null != empitemList && empitemList.size() > 0) {
            for (TlEmergentResplanItem item : empitemList) {
                item.setResplanid(tlEmergentResplan.getId());
                item.setWorktype("emp");
                askemp.add(item.getClassname());
                tlEmergentResplanItemService.insert(item);
            }
            tlEmergentResplan.setAskemp(String.join(",", askemp));

        }

        tlEmergentResplanMapper.updateById(tlEmergentResplan);
        return AjaxResult.success("操作成功");

    }

    @Override
    @Transactional
    public AjaxResult deletebyid(TlEmergentResplan tlEmergentResplan) throws HssException {
        String id = tlEmergentResplan.getId();
        tlEmergentResplanItemService.deletebyid(id);
        tlEmergentResplanMapper.deleteById(id);
        return AjaxResult.success("操作成功");
    }

    @Override
    @Transactional
    public AjaxResult deletebatchbyid(TlEmergentResplan tlEmergentResplan) throws HssException {

        String ids = tlEmergentResplan.getIds();
        String[] idArray = ids.split(",");
        tlEmergentResplanMapper.deleteBatchIds(Arrays.asList(idArray));

        for (String id:
                idArray) {
            tlEmergentResplanItemService.deletebyid(id);
        }

        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult changeStatus(TlEmergentResplan tlEmergentResplan) throws HssException {

        String username = LoginUtils.getUser().getAccount();
        String ids = tlEmergentResplan.getIds();
        String[] idArray = ids.split(",");
        tlEmergentResplan.setUpdateby(username);
        tlEmergentResplan.setUpdatetime(new Date());

        UpdateWrapper<TlEmergentResplan> tlEmergentResplanUpdateWrapper = new UpdateWrapper<>();
        tlEmergentResplanUpdateWrapper.lambda().in(TlEmergentResplan::getId, idArray);

        int i = tlEmergentResplanMapper.update(tlEmergentResplan,tlEmergentResplanUpdateWrapper);

        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }
    @Override
    public TlEmergentResplan getDetail(TlEmergentResplan tlEmergentResplan) throws HssException {
        String id = tlEmergentResplan.getId();
        tlEmergentResplan = tlEmergentResplanMapper.selectById(id);
        QueryWrapper<TlCarType> tlCarTypeWrapper = new QueryWrapper<>();
        QueryWrapper<TlWorkType> tlWorkTypeWrapper = new QueryWrapper<>();
        List<TlCarType> resultListCarList = tlCarTypeMapper.selectList(tlCarTypeWrapper);
        List<TlWorkType> resultListWorkList = tlWorkTypeMapper.selectList(tlWorkTypeWrapper);
        Map<String, List<TlCarType>> resultListCarListMapByType = resultListCarList.stream().collect(Collectors.groupingBy(TlCarType::getId));
        Map<String, List<TlWorkType>> resultListWorkListMapByLevel = resultListWorkList.stream().collect(Collectors.groupingBy(TlWorkType::getId));

        Map map = new HashMap();
        map.put("worktype", "car");
        map.put("resplanid", id);

        List<TlEmergentResplanItem> caritemList = tlEmergentResplanItemMapper.selectByMap(map);
        if (null != caritemList && caritemList.size() > 0) {
            caritemList.forEach(t -> {
                t.setClassname(resultListCarListMapByType.get(t.getClassid()).get(0).getTypename());
            });

            tlEmergentResplan.setCardateils(caritemList);
        }
        Map map2 = new HashMap();
        map2.put("worktype", "emp");
        map2.put("resplanid", id);
        List<TlEmergentResplanItem> empitemList = tlEmergentResplanItemMapper.selectByMap(map2);
        if (null != empitemList && empitemList.size() > 0) {
            empitemList.forEach(t -> {
                t.setClassname(resultListWorkListMapByLevel.get(t.getClassid()).get(0).getWorktype());
            });

            tlEmergentResplan.setEmpdateils(empitemList);
        }
        return tlEmergentResplan;
    }

    @Override
    public List<TlEmergentResplan> getSelectList(TlEmergentResplan tlEmergentResplan) {
        QueryWrapper<TlEmergentResplan> tlEmergentResplanQueryWrapper = new QueryWrapper<>();
        tlEmergentResplanQueryWrapper.lambda().eq(TlEmergentResplan::getStatus, tlEmergentResplan.getStatus());
        List<TlEmergentResplan> tlEmergentResplanList = tlEmergentResplanMapper.selectList(tlEmergentResplanQueryWrapper);

        QueryWrapper<TlCarType> tlCarTypeWrapper = new QueryWrapper<>();
        QueryWrapper<TlWorkType> tlWorkTypeWrapper = new QueryWrapper<>();
        List<TlCarType> resultListCar = tlCarTypeMapper.selectList(tlCarTypeWrapper);
        Map<String, List<TlCarType>> tlCarTypeCollect = resultListCar.stream().collect(Collectors.groupingBy(TlCarType::getTypename));
        List<TlWorkType> resultListWork = tlWorkTypeMapper.selectList(tlWorkTypeWrapper);
        Map<String, List<TlWorkType>> tlWorkTypeCollect = resultListWork.stream().collect(Collectors.groupingBy(TlWorkType::getWorktype));

        for (TlEmergentResplan tlEmergentResplan1 : tlEmergentResplanList) {
            List<TlCarType> tlCarTypeList = new ArrayList<>();
            List<TlWorkType> tlWorkTypeList = new ArrayList<>();
           if(null!=tlEmergentResplan1.getAskcar()){
              String[] carSplit = tlEmergentResplan1.getAskcar().split(",");
                  for (String carType : carSplit) {
                    if (null != tlCarTypeCollect.get(carType)) {
                      tlCarTypeList.addAll(tlCarTypeCollect.get(carType));
                      tlEmergentResplan1.setTlCarTypes(tlCarTypeList);

                  }
              }
          }
            if(null!=tlEmergentResplan1.getAskemp()){
                String[] empSplit = tlEmergentResplan1.getAskemp().split(",");
                for (String empType : empSplit) {
                    if (null != tlWorkTypeCollect.get(empType)) {
                        tlWorkTypeList.addAll(tlWorkTypeCollect.get(empType));
                        tlEmergentResplan1.setTlWorkTypes(tlWorkTypeList);

                    }
                }
            }


        }
        return tlEmergentResplanList;
    }

    @Override
    @DataScope(deptAlias = "deptid", userAlias = "createby, updateby")
    public TlEmergentResPlanVO getList(BaseEntity entity, TlEmergentResplan tlEmergentResplan) throws HssException {
        Long page = StringUtils.isEmpty(tlEmergentResplan.getPage()) ? 1 : tlEmergentResplan.getPage();
        Long size = StringUtils.isEmpty(tlEmergentResplan.getSize()) ? 10 : tlEmergentResplan.getSize();

        Map<String, Object> map = new HashMap();
        map.put("resplanname", tlEmergentResplan.getResplanname());
        map.put("emergenttypeid", tlEmergentResplan.getEmergenttypeid());
        map.put("emergentlevelid", tlEmergentResplan.getEmergentlevelid());
        map.put("status", tlEmergentResplan.getStatus());
        map.put("param", entity.getParams());

        Page<TlEmergentResplan> listPage = new Page<>(page, size, true);
        IPage<TlEmergentResplan> iPage = tlEmergentResplanMapper.listTlEmergentResplan(listPage, map);

        List<TlEmergentResplan> tlEmergentResplanList = iPage.getRecords();
        for (TlEmergentResplan tlEmergentResplan1 : tlEmergentResplanList) {
            //根据id查询计划
            List<TlEmergentPlan> tlEmergentPlanList = tlEmergentPlanMapper.findTlEmergentPlanByEmergentLevelId(tlEmergentResplan1.getId());
            tlEmergentResplan1.setTlEmergentPlanList(tlEmergentPlanList);
        }
        TlEmergentResPlanVO tlEmergentResPlanVO = new TlEmergentResPlanVO();
        tlEmergentResPlanVO.setSize(iPage.getSize());
        tlEmergentResPlanVO.setPage(iPage.getPages());
        tlEmergentResPlanVO.setTotal(iPage.getTotal());
        tlEmergentResPlanVO.setCurrent(iPage.getCurrent());
        tlEmergentResPlanVO.setTlEmergentResPlanList(tlEmergentResplanList);
        return tlEmergentResPlanVO;
    }

    @Override
    public EmergentPlanCalendar emergentPlanCalendar() throws HssException {
        EmergentPlanCalendar emergentPlanCalendar = new EmergentPlanCalendar();

        // 计划的
        QueryWrapper<TlEmergentPlan> tlEmergentPlanWrapper = new QueryWrapper<>();
        List<TlEmergentPlan> tlEmergentPlanList = tlEmergentPlanMapper.selectList(tlEmergentPlanWrapper);
        emergentPlanCalendar.setPlanCount(tlEmergentPlanList.size());
        //预案
        QueryWrapper<TlEmergentResplan> tlEmergentResplanWrapper = new QueryWrapper<>();
        List<TlEmergentResplan> tlEmergentResplanList = tlEmergentResplanMapper.selectList(tlEmergentResplanWrapper);
        emergentPlanCalendar.setResplanCount(tlEmergentResplanList.size());
        Map<String, List<TlEmergentResplan>> tlEmergentResplanMapByType = tlEmergentResplanList.stream().collect(Collectors.groupingBy(TlEmergentResplan::getEmergenttypeid));
        Map<String, List<TlEmergentResplan>> tlEmergentResplanMapByLevel = tlEmergentResplanList.stream().collect(Collectors.groupingBy(TlEmergentResplan::getEmergentlevelid));

        QueryWrapper<TlEmergentDictType> tlEmergentDictTypeQueryWrapper = new QueryWrapper<>();
        List<TlEmergentDictType> tlEmergentDictTypeList = tlEmergentDictTypeMapper.selectList(tlEmergentDictTypeQueryWrapper);

        List<TlEmergentDictLevel> tlEmergentDictLevels1 = tlEmergentDictLevelService.list();
        List<EmergentPlanLevel> emergentPlanLevelList = new ArrayList<>();
        List<EmergentPlantype> emergentPlanTypeList = new ArrayList<>();
        EmergentPlantype emergentPlantype1 = new EmergentPlantype();
        emergentPlantype1.setTypeName("全部");
        emergentPlantype1.setTypeCount(0);
        emergentPlantype1.setEmergentPlanLevelList(emergentPlanLevelList);
        emergentPlanTypeList.add(emergentPlantype1);
        tlEmergentDictTypeList.forEach(t -> {
            EmergentPlantype emergentPlantype = new EmergentPlantype();
            emergentPlantype.setTypeName(t.getEventtype());
            emergentPlantype.setTypeCount(0);
            if (null != tlEmergentResplanList.stream().
                    filter(t1 -> t1.getEmergenttypeid().equals(t.getId()))) {
                tlEmergentResplanList.stream().
                        filter(t1 -> t1.getEmergenttypeid().equals(t.getId())).forEach(t3 -> {

                    t3.setEmergenttype(t.getEventtype());
                });
            }

            if (null != tlEmergentResplanMapByType.get(t.getId())) {
                emergentPlantype.setTypeCount(tlEmergentResplanMapByType.get(t.getId()).size());

            }
            if (emergentPlantype.getTypeCount() > 0) {
                emergentPlantype.setEmergentPlanLevelList(new ArrayList<>());

                Map<String, List<TlEmergentResplan>> tlEmergentResplanMapByLevel0 = tlEmergentResplanList.stream().
                        filter(t1 -> t1.getEmergenttypeid().equals(t.getId())).
                        collect(Collectors.groupingBy(TlEmergentResplan::getEmergentlevelid));

                setEmergentPlanLevelList(emergentPlantype.getEmergentPlanLevelList(), tlEmergentDictLevels1, tlEmergentResplanMapByLevel0);
                emergentPlantype1.setTypeCount(emergentPlantype1.getTypeCount() + emergentPlantype.getTypeCount());
                emergentPlanTypeList.add(emergentPlantype);
            }
        });
        emergentPlanCalendar.setEmergentPlantypeList(emergentPlanTypeList);
        setEmergentPlanLevelList(emergentPlanLevelList, tlEmergentDictLevels1, tlEmergentResplanMapByLevel);
        return emergentPlanCalendar;
    }

    private void setEmergentPlanLevelList(List<EmergentPlanLevel> emergentPlanLevelList, List<TlEmergentDictLevel> tlEmergentDictLevels1, Map<String, List<TlEmergentResplan>> tlEmergentResplanMapByLevel) {
        tlEmergentDictLevels1.forEach(t -> {
            EmergentPlanLevel emergentPlanLevel = new EmergentPlanLevel();
            emergentPlanLevel.setLevelName(t.getLevel());
            emergentPlanLevel.setLevelId(t.getId());
            emergentPlanLevel.setLevelCount(0);
            emergentPlanLevel.setLevelColor(t.getColor());
            if (null != tlEmergentResplanMapByLevel.get(t.getId())) {
                emergentPlanLevel.setLevelCount(tlEmergentResplanMapByLevel.get(t.getId()).size());
            }
            if (emergentPlanLevel.getLevelCount() > 0) {
                emergentPlanLevel.setEmergentPlantypeListList(new ArrayList<>());
                tlEmergentResplanMapByLevel.get(t.getId()).forEach(t1 -> {
                    EmergentResPlanVo emergentResPlanVo = new EmergentResPlanVo();
                    emergentResPlanVo.setResPlanName(t1.getResplanname());
                    emergentResPlanVo.setResPlanId(t1.getId());
                    emergentResPlanVo.setLevelId(t1.getEmergentlevelid());
                    emergentResPlanVo.setRemark(t1.getRemark());
                    emergentResPlanVo.setAskCar(t1.getAskcar());
                    emergentResPlanVo.setAskEmp(t1.getAskemp());
                    emergentResPlanVo.setEmergentLevel(t.getLevel());
                    emergentResPlanVo.setEmergentType(t1.getEmergenttype());

                    emergentPlanLevel.getEmergentPlantypeListList().add(emergentResPlanVo);
                });
                emergentPlanLevelList.add(emergentPlanLevel);
            }
        });
    }
}
